package org.colcon.web.server;

import org.colcon.web.client.ColConService;
import org.colcon.web.model.User;
import org.colcon.web.model.framework.IContainer;
import org.colcon.web.model.framework.IItem;
import org.colcon.web.model.parsers.CLIParser;

import com.google.gwt.user.server.rpc.RemoteServiceServlet;

public class ColConServiceImpl 
	extends RemoteServiceServlet 
	implements ColConService 
{
	private static final long serialVersionUID = 5492849777369331376L;

	public ColConServiceImpl()
	{
		Model.init();
	}
	
	public String execute(String cmd)
	{
		return CLI.execute(cmd);
	}
	
	public String get(String path)
	{
		return execute("get " + path);
	}
	
	public String[] open(String path)
	{
		String str = get(path);
		
		IItem item = CLIParser.parseItem(str);
		
		if(item == null || !(item instanceof IContainer))
			return null;
		
		String[] children = ((IContainer)item).getChildren();
		
		String[] array = new String[children.length];
		
		for(int i = 0; i < array.length; i++)
			array[i] = get(path + '/' + children[i]);
		
		return array;
	}
	
	public User authenticate(String id, String password)
	{
		User user = (User) Model.getUser(id);
		
		if(user == null || !user.getPassword().equals(password))
			return null;
		
		return user;
	}
	
	/*public Item get(String path)
	{
		return (Item) Model.get(path);
	}*/
}
